package org.grow.bill.service;

import org.grow.basic.dto.BatchIntentionDto;
import org.grow.bill.dao.CommodityBatchDao;
import org.grow.bill.dao.PurchaseBillDao;
import org.grow.bill.entity.CommodityBatch;
import org.grow.bill.entity.PurchaseBill;
import org.grow.bill.exception.PurchaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 21-8-11
 */

@Service
public class PurchaseBillService {
    @Autowired
    private PurchaseBillDao purchaseBillDao;
    @Autowired
    private CommodityBatchDao commodityBatchDao;

    @Autowired
    private PurchaseBillFeign purchaseBillFeign;
    @Transactional
    public void txInsert(PurchaseBill purchaseBill) {
        int insert = purchaseBillDao.insert(purchaseBill);
        if (insert==0) throw new PurchaseException("保存purchaseBill异常,事务整体回滚");

        List<CommodityBatch> commodityBatches =
                purchaseBill.getCommodityBatches();
        for (CommodityBatch commodityBatch : commodityBatches) {
            int insert1 = commodityBatchDao.insert(commodityBatch);
            if (insert1==0) throw new PurchaseException("保存batch异常,事务整体回滚");
//            改成远程调用。
//            int update = commodityBatchDao.updateStorageIntentionBy(commodityBatch);
            BatchIntentionDto batchIntentionDto = new BatchIntentionDto();
            batchIntentionDto.setCommodityCode(commodityBatch.getCommodityFk());
            batchIntentionDto.setQuantity(commodityBatch.getAdvanceQuantity());
//            todo :cookie / token
            Integer update = purchaseBillFeign.updateIntentionStock(batchIntentionDto);


            if (update == 0) throw new PurchaseException("更新意向库存异常,事务整体回滚");
        }
/*      异常捕获再抛出
        try {
            try {
                try{
                   10/0
                }catch(Exception e){
                    System.out.println();
                    throw e;
                }
            } catch (Exception e) {
                System.out.println("dddd"+e);
                throw e;
            }
        } catch (Exception e) {
            System.out.println("sanci");
            throw e;
        }*/
//        int k = 10/2;
//        int s = k*3;
//        int t = s%3;

    }
}
